extends Node2D

@export var monster_create_time : int = 1.8
# 玩家和怪物场景（在编辑器中设置）
@export var player_scene: PackedScene
@export var monster_scene: PackedScene

@onready var exp_bar: TextureProgressBar = $TopBarCanvaLayer/ExpBar
@onready var exp_label: Label = $TopBarCanvaLayer/ExpLabel

# 生成位置配置
var x_positions = [4, 124, 244, 364, 484, 604]
var y_positions = [56, 186, 316, 446, 576]

# 存储当前实体
var player = null
var monsters = []

func _ready():
	# 生成初始玩家（使用延迟调用）
	spawn_player()
	
	# 设置怪物生成计时器
	var timer = Timer.new()
	timer.wait_time = monster_create_time
	timer.autostart = true
	timer.timeout.connect(_on_spawn_timer_timeout)
	add_child(timer)
	
	
func spawn_player():
	# 生成玩家实例
	player = player_scene.instantiate()
	
	# 设置随机位置
	player.position = get_unique_position()
	
	# 将玩家添加到组中
	player.add_to_group("player")
	
	# 连接玩家的经验值变化信号
	player.exp_changed.connect(_on_player_exp_changed)
	
	# 延迟添加到场景
	get_tree().root.add_child.call_deferred(player)
	print("玩家生成在位置: ", player.position)

func try_spawn_monster():
	# 如果已达最大怪物数量则跳过
	if monsters.size() >= 6:
		return false
	
	# 尝试生成怪物
	var new_pos = get_unique_position()
	if new_pos != Vector2.ZERO:
		var monster = monster_scene.instantiate()
		monster.position = new_pos
		get_tree().root.add_child.call_deferred(monster)
		monsters.append(monster)
		print("怪物生成在位置: ", monster.position)
		return true
	
	print("警告：找不到有效位置生成怪物")
	return false

func get_unique_position():
	# 获取所有现有实体的位置
	var occupied_positions = []
	if is_instance_valid(player) and player:
		occupied_positions.append(player.position)
	
	for monster in monsters:
		if is_instance_valid(monster) and monster:
			occupied_positions.append(monster.position)
	
	# 尝试寻找有效位置
	var valid_positions = []
	for x in x_positions:
		for y in y_positions:
			var candidate = Vector2(x, y)
			
			# 检查是否与现有位置冲突
			var collision = false
			for pos in occupied_positions:
				if pos.distance_to(candidate) < 50:  # 50像素最小间距
					collision = true
					break
			
			if not collision:
				valid_positions.append(candidate)
	
	# 随机返回一个有效位置
	if valid_positions.size() > 0:
		return valid_positions[randi() % valid_positions.size()]
	
	return Vector2.ZERO  # 无有效位置

func _on_spawn_timer_timeout():
	# 清理无效的怪物引用
	monsters = monsters.filter(func(m): return is_instance_valid(m) and m)
	
	# 补充怪物到6个
	var needed = 6 - monsters.size()
	if needed > 0:
		var spawn_count = min(needed, 2)  # 每次最多生成2个
		for i in range(spawn_count):
			try_spawn_monster.call_deferred()

# 玩家经验值变化处理函数
func _on_player_exp_changed(current_exp, max_exp):
	if is_instance_valid(exp_bar):
		# 计算经验值百分比
		var exp_percent = float(current_exp) / max_exp * 100
		exp_bar.value = exp_percent
	
	# 如果需要显示数值
	if is_instance_valid(exp_label):
		exp_label.text = "%d / %d" % [current_exp, max_exp]
